package com.monkey.core.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.monkey.core.ErrorCode;
import com.monkey.service.AdminService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * desc: 切面
 * auth: chenxiaobin
 * data: 2017/4/1.
 */
@Aspect
@Component
public class ControllerAopLogger {
    private static Logger logger = LoggerFactory.getLogger(ControllerAopLogger.class);

    @Resource
    private AdminService adminService = null;

    @Pointcut("execution(public * com.monkey.controller.*.*_log(..))")
    public void loggerRestController() {
    }

    @Around("loggerRestController()")
    public Map<String, Object> logAround(ProceedingJoinPoint pjp) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String className = pjp.getTarget().getClass().getSimpleName();
        String funcName = pjp.getSignature().getName();

        // 记录下请求内容
        Object[] args = pjp.getArgs();
        if (args.length > 2) {
            logger.info("--> class:{}, func:{}, args: {}", className, funcName, args[1]);
        } else {
            logger.info("--> class:{}, func:{}, args: {}", className, funcName, args);
        }

        if (!adminService.isAllow()) {
            logger.info("<-- not allow");
            Map<String, Object> ret = new HashMap<>();
            ret.put("code", ErrorCode.SERVICE_DISABLE);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.SERVICE_DISABLE));
            return ret;
        }

        // 处理页面信息
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> ret = (Map<String, Object>) pjp.proceed();
            logger.info("<-- class:{}, func:{}, ret:{}", className, funcName, mapper.writeValueAsString(ret));
            return ret;
        } catch (Exception e) {
            logger.info("<-- class:{}, func:{}, error:{}", className, funcName, e);
            Map<String, Object> ret = new HashMap<>();
            ret.put("code", ErrorCode.EXCEPTION_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.EXCEPTION_ERROR));
            return ret;
        }
    }
}
